<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isView ? '查看白名单' : '白名单管理'" v-model="visible" append-to-body width="800px"
    @close="handleClose">
    <template v-if="!isView">
      <div class="flex items-center gap-2">
        新增规则: <el-radio-group v-model="form.type">
          <el-radio v-for="(d, i) in options.type" :key="i" :label="d.value">{{ d.label }}</el-radio>
        </el-radio-group>
      </div>
      <div class="flex gap-2 mb-3 mt-1">
        <VSelect v-model="form.platform_id" placeholder="请选择平台" :options="options.platform" class="w-full"
          @change="platformChange" />
        <template v-if="form.type">
          <VSelect v-model="form.site_id" placeholder="请选择站点" :options="siteOptions" class="w-full"
            @change="({ option }) => (form.site_name = option.label)" />
          <VCascader :key="categoryKey" v-model="form.category_id" placeholder="请选择" type="4" :site_id="form.site_id"
            class="w-full" @change="({ labels }) => (form.category_name = labels.join(' > '))" />
        </template>
        <template v-else>
          <VSelect v-model="form.shop_id" placeholder="请选择店铺" :options="shopOptions" class="w-full"
            @change="({ option }) => (form.shop_name = option.label)" />
        </template>
        <el-button type="primary"
          :disabled="(form.type && (!form.platform_id || !form.site_id || !form.category_id)) || (!form.type && (!form.platform_id || !form.shop_id))"
          @click="add">添加</el-button>
      </div>
    </template>
    <vxe-table :data="data.white_list" size="small">
      <vxe-column title="序号" type="seq" width="60"></vxe-column>
      <vxe-column title="类型" field="type_name" width="100"></vxe-column>
      <vxe-column title="平台" field="platform_name" width="100"></vxe-column>
      <vxe-column title="范围" field="scope_info">
        <template #default="{ row }">
          <div v-html="row.scope_info"></div>
        </template>
      </vxe-column>
      <vxe-column v-if="!isView" title="操作" width="80">
        <template #default="{ rowIndex }">
          <el-link type="primary" @click="data.white_list.splice(rowIndex, 1)">移除</el-link>
        </template>
      </vxe-column>
    </vxe-table>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button v-if="!isView" type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { watch } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const shopOptions = computed(() => props.options.platform_shop?.find(d => d.platform_id === form.value.platform_id)?.shops?.map(d => ({ label: d.shop_name, value: d.shop_id })) || [])
const siteOptions = ref([])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const data = ref([])

const emit = defineEmits(['close', 'success'])

const add = () => {
  const { shop_name, site_name, category_name, type } = form.value
  const scope_info = type ? `站点: ${site_name} ,  分类: ${category_name}` : `店铺: ${shop_name}`
  if (data.value.white_list.find(d => d.scope_info === scope_info)) {
    ElMessage.error('请勿重复添加')
    return
  }
  data.value.white_list.push({ ...form.value, scope_info })
  form.value = { type, type_name: props.options.type.find(d => d.value === type)?.label || '' }
}

watch(
  () => form.value.type,
  (type) => {
    form.value = { type, type_name: props.options.type.find(d => d.value === type)?.label || '' }
  }
)

const categoryKey = ref(0)
watch(
  () => form.value.site_id,
  (val) => categoryKey.value++
)

const platformChange = ({ value, option }) => {
  form.value.platform_name = option.label
  form.value.shop = ''
  form.value.site_id = ''
  form.value.category_id = ''
  if (form.value.type) {
    api.getPlatform({ platform_id: value }).then(res => {
      siteOptions.value = res.data.map(d => ({ label: d.site_name, value: d.site_id }))
    })
  }
}

// 打开弹窗
const isView = ref(false)
const open = async (pw_id, option) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  isView.value = option?.view
  form.value = { type: 0 }
  data.value = []
  const res = await api.whitelistDetail({ pw_id })
  data.value = res.data
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

// 提交
const create = async () => {
  loadings.create = true
  api.whitelist(data.value).then(res => {
    ElMessage.success('保存成功')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>